package lru;


import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * https://leetcode.cn/problems/lru-cache/?favorite=2cktkvj
 *
 * 题解：https://mp.weixin.qq.com/s/b0YVCccJ8mFP6lI-1NiQOQ
 */
public class _146_LRU缓存 {

    int cap;

    Map<Integer,Integer> map = new LinkedHashMap<>();

    public _146_LRU缓存(int capacity) {
        this.cap = capacity;
    }

    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        int val = map.get(key);
        makeRecenty(key);
        return val;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            map.put(key,value);
            makeRecenty(key);
        }else {
            if(map.size() >= cap) {
                map.remove(map.keySet().iterator().next());
            }
            map.put(key,value);
        }
    }


    private void makeRecenty(int key) {
        int val = map.get(key);
        map.remove(key);
        map.put(key, val);
    }


}
